import { WechatService } from '@app/wechat';
import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import { User } from '@app/db/entity/User';
import { USER_SOURCE } from 'constant/USER_SOURCE';
import { UserService } from '../user/user.service';
import { ConfigureService } from '@app/configure';
import { JwtVerifyService } from '@app/jwt-verify';

@Injectable()
export class LoginService {
    private jwtExpire = 0
    constructor(
        private readonly userService:UserService,
        private readonly wechat:WechatService,
        private readonly db:DbService,
        private readonly config:ConfigureService,
        private readonly jwt:JwtVerifyService,
    ) {
        this.jwtExpire = Number(this.config.get('JWT_EXPIRE'))
    }

    public async login(code:string, isWx:boolean) {
       
        const data = await this.wechat.login(code)
        if(data == null) return null

        //let openid = isWx ? data.openid : data.userId
        const openid = data.openid
        
        const time = Math.floor(Date.now() / 1000)
        let user:KeyToValueType<User> = await this.db.user.findOne({openid : openid}, ['id', 'source', 'nickname', 'avatar', 'phone'])

        if(!user) { //还没有的
            // user = new User();{
            //     openid,
            //     source : isWx ? USER_SOURCE.WX : USER_SOURCE.ALI,
            //     registerTime : time,
            //     phone : null
            // }
            user = new User()
            user.amount = 0
            user.rewardAmount = 0
            user.freezeAmount = 0
            user.openid = openid
            user.source = isWx ? USER_SOURCE.WX : USER_SOURCE.ALI
            user.registerTime = time
            user.phone = null

            const res = await this.db.user.insert(user)

            if(!res) return null

            user.id = res.rows[0].id
        }else {
            this.db.user.update({id : user.id}, {
                lastLoginTime : time,
                //lastIp : ip
            })
        }

        let cacheData:any = {
            source : user.source,
            openid : openid
        }

        if(isWx) {
            cacheData.session_key = data.session_key
            if(data.unionid) {
                cacheData.unionid = data.unionid
            }
        }else {

        }

        

        this.userService.setCache(user.id, cacheData)

        const accessToken = this.jwt.sign({key : user.id, id : Math.ceil((time - 1030) / 263), time : time}, this.jwtExpire)
        
       
        return {
            accessToken,
            refreshToken : '',
            expire : this.jwtExpire,
            user : {
                nickname : user.nickname || '',
                avatar : user.avatar || '',
                phoneAuth : user.phone != null
            }
        }

    }
}
